<template>
  <Header :getGoods="getGoods" />
  <div class="release-container">
    <div class="release-baseInfo">
      <!-- 商品基本信息 -->
      <div class="release-name">
        <input type="text" placeholder="请填写商品名称" v-model="formData.name" maxlength="100" />
      </div>
      <div class="release-price">
        <input type="text" placeholder="请填写商品简介" v-model="formData.description" maxlength="300" />
      </div>
      <div class="release-blurb">
        <input type="number" placeholder="请填写商品价格" v-model.number="formData.price" min="0" step="0.01" />
      </div>
    </div>

    <div class="release-select-one">
      <!-- 选择项部分 -->
      <div class="release-category">
        <select v-model="formData.categoryId">
        <option value="">请选择商品分类</option>
        <option v-for="category in categories" :key="category.id" :value="category.id">
          {{ category.name }}
        </option>
      </select>
      </div>

      <div class="release-free-post">
        <select v-model="formData.freePostId">
          <option value="">请选择是否包邮</option>
          <option v-for="option in freePostOptions" :key="option.id" :value="option.id">
            {{ option.name }}
          </option>
        </select>
      </div>

      <div class="release-page-options">
        <select v-model="formData.pageOptionId">
          <option value="">请选择包装选项</option>
          <option v-for="option in pageOptions" :key="option.id" :value="option.id">
            {{ option.name }}
          </option>
        </select>
      </div>
    </div>

    <div class="release-select-two">
      <!-- 选择项部分 -->
      <div class="release-Fineness">
        <select v-model="formData.conditionId">
          <option value="">请选择商品的使用程度</option>
          <option v-for="option in conditionOptions" :key="option.id" :value="option.id">
            {{ option.name }}
          </option>
        </select>
      </div>

      <div class="release-version">
        <select v-model="formData.versionId">
          <option value="">请选择版本</option>
          <option v-for="option in versionOptions" :key="option.id" :value="option.id">
            {{ option.name }}
          </option>
        </select>
      </div>

      <div class="release-Platform">
        <select v-model="formData.platformId">
          <option value="">请选择平台</option>
          <option v-for="option in PlatformOptions" :key="option.id" :value="option.id">
            {{ option.name }}
          </option>
        </select>
      </div>
    </div>

    <div class="release-intro-container">
      <textarea class="release-intro" placeholder="大胆且详细地介绍你的商品吧!" v-model="formData.introduction"></textarea>
    </div>

    <div class="release-upload-container">
      <!-- 单图片上传部分 -->
      <p>请为你的宝贝挑选一张合适的展示封面</p>
      <div class="release-box-showInfo">
        <div
          class="release-section"
          @click="triggerFileInput"
          :style="{ backgroundImage: filePreviewUrl ? `url(${filePreviewUrl})` : '' }"
        >
          <el-icon v-if="!filePreviewUrl">
            <Plus />
          </el-icon>
          <div v-if="filePreviewUrl" class="delete-button" @click.stop="removeFile">-</div>
          <input
            type="file"
            ref="fileInput"
            @change="handleFileChange"
            style="display: none;"
          />
        </div>
      </div>

      <!-- 多图片上传部分 -->
      <p>请为你的宝贝上传更多图片(最多九张)</p>
      <div class="multi-upload-container">
        <div
          v-for="(image, index) in formData.images"
          :key="index"
          class="release-section"
          @click="!image.url && triggerMultiFileInput(index)"
        >
          <el-icon v-if="!image.url">
            <Plus />
          </el-icon>
          <img v-if="image.url" :src="image.url" alt="Uploaded Image" />
          <div v-if="image.url" class="delete-button" @click.stop="removeImage(index)">-</div>
          <input
            type="file"
            :ref="(el) => { multiFileInputs[index] = el as HTMLInputElement | null; }"
            @change="(event) => handleMultiFileChange(event, index)"
            style="display: none;"
          />
        </div>
      </div>
    </div>

    <div class="release-button-container">
      <button class="release-button" @click="submitForm">确认发布</button>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted } from 'vue';
import { Plus } from '@element-plus/icons-vue';
import axios from 'axios';
import '../css/userInfo.css';
import Header from './Header.vue';

const token = localStorage.getItem('token');
const loginId = Number(localStorage.getItem('userId'));


const fileInput = ref<HTMLInputElement | null>(null);
const filePreviewUrl = ref<string | null>(null);
const multiFileInputs = ref<Array<HTMLInputElement | null>>([]);
const formData = ref({
  loginId:0,
  name: '',
  description: '',
  price: '',
  categoryId: '',
  freePostId: '',
  pageOptionId: '',
  conditionId: '',
  versionId: '',
  platformId: '',
  introduction: '',
  coverImage: null as File | null,
  images: Array.from({ length: 1 }, () => ({ file: null as File | null, url: null as string | null }))
});

const freePostOptions = ref<Array<{ id: number; name: string }>>([]);
const categories = ref<Array<{ id: number; name: string }>>([]);
const conditionOptions = ref<Array<{ id: number; name: string }>>([]);
const versionOptions = ref<Array<{ id: number; name: string }>>([]);
const PlatformOptions = ref<Array<{ id: number; name: string }>>([]);
const pageOptions = ref<Array<{ id: number; name: string }>>([]);



const getCategoriesLink = "http://localhost:8080/common/getCategories";
const getAllFreePostLink = "http://localhost:8080/goods/getAllFreePost";
const getAllPageLink = "http://localhost:8080/goods/getAllPage";
const getAllFinenessLink = "http://localhost:8080/goods/getAllFineness";
const getAllVersionLink = "http://localhost:8080/goods/getAllVersion";
const getAllPlatformLink = "http://localhost:8080/goods/getAllPlatform";
const uploadLink = "http://localhost:8080/goods/upload";


const getCategories = async () => {
  try {
    const response = await axios.get(getCategoriesLink);
    if (response.data.state) {
      categories.value = response.data.data;
    } else {
      console.error('Failed to fetch categories:', response.data.errMessage);
    }
  } catch (error) {
    console.error('Failed to fetch categories:', error);
  }
};
const getAllFreePost = async () => {
  try {
    const response = await axios.get(getAllFreePostLink);
    if (response) {
      freePostOptions.value = response.data.data;
    } else {
      console.error('Failed to fetch free post options');
    }
  } catch (error) {
    console.error('Failed to fetch free post options:', error);
  }
};
const getAllPage = async () => {
  try {
    const response = await axios.get(getAllPageLink);
    pageOptions.value = response.data.data;
  } catch (error) {
    console.error('Failed to fetch free post options:', error);
  }
};
const getAllFineness = async () => {
  try {
    const response = await axios.get(getAllFinenessLink);
    conditionOptions.value = response.data.data;
  } catch (error) {
    console.error('Failed to fetch free post options:', error);
  }
};
const getAllVersion = async () => {
  try {
    const response = await axios.get(getAllVersionLink);
    versionOptions.value = response.data.data;
  } catch (error) {
    console.error('Failed to fetch free post options:', error);
  }
};
const getAllPlatform = async () => {
  try {
    const response = await axios.get(getAllPlatformLink);
    PlatformOptions.value = response.data.data;
  } catch (error) {
    console.error('Failed to fetch free post options:', error);
  }
};

const handleFileChange = (event: Event) => {
  const input = event.target as HTMLInputElement;
  if (input.files && input.files.length > 0) {
    const file = input.files[0];
    if (file && file.type.startsWith('image/') && file.size <= 5 * 1024 * 1024) { // 限制文件类型为图片，大小不超过 5MB
      formData.value.coverImage = file;

      const reader = new FileReader();
      reader.onload = (e) => {
        filePreviewUrl.value = e.target?.result as string;
      };
      reader.readAsDataURL(file);
    } else {
      alert('请上传有效的图片文件，不超过 5MB');
    }
  }
};

const handleMultiFileChange = (event: Event, index: number) => {
  const input = event.target as HTMLInputElement;
  if (input.files && input.files.length > 0) {
    const file = input.files[0];
    if (file && file.type.startsWith('image/') && file.size <= 5 * 1024 * 1024) { // 限制文件类型为图片，大小不超过 5MB
      const reader = new FileReader();
      reader.onload = (e) => {
        formData.value.images[index].url = e.target?.result as string | null;
      };
      reader.readAsDataURL(file);
      formData.value.images[index].file = file;

      if (formData.value.images.length < 9) {
        formData.value.images.push({ file: null, url: null });
      }
    } else {
      alert('请上传有效的图片文件，不超过 5MB');
    }
  }
};


const removeFile = () => {
  formData.value.coverImage = null;
  filePreviewUrl.value = null;
  if (fileInput.value) {
    fileInput.value.value = '';
  }
};

const removeImage = (index: number) => {
  formData.value.images.splice(index, 1);
  if (multiFileInputs.value[index]) {
    multiFileInputs.value[index]!.value = '';
  }
  // 确保最后一个元素为空对象
  if (formData.value.images.length === 0 || formData.value.images[formData.value.images.length - 1].url) {
    formData.value.images.push({ file: null, url: null });
  }
};

const triggerFileInput = () => {
  if (fileInput.value) {
    fileInput.value.click();
  }
};

const triggerMultiFileInput = (index: number) => {
  if (multiFileInputs.value[index]) {
    multiFileInputs.value[index]!.click();
  }
};

const submitForm = async () => {
  // 验证必填项
  if (!formData.value.name || !formData.value.price || !formData.value.categoryId) {
    alert('请填写所有必填项');
    return;
  }

  // 验证下拉框
  if (!formData.value.categoryId) {
    alert('请选择商品分类');
    return;
  }
  if (!formData.value.freePostId) {
    alert('请选择是否包邮');
    return;
  }
  if (!formData.value.pageOptionId) {
    alert('请选择包装选项');
    return;
  }
  if (!formData.value.conditionId) {
    alert('请选择商品的使用程度');
    return;
  }
  if (!formData.value.versionId) {
    alert('请选择版本');
    return;
  }
  if (!formData.value.platformId) {
    alert('请选择平台');
    return;
  }

  // 验证图片上传
  if (!formData.value.coverImage) {
    alert('请上传封面图片');
    return;
  }

  const hasImages = formData.value.images.some(image => image.file !== null);
  if (!hasImages) {
    alert('请上传至少一张商品图片');
    return;
  }

  try {
    const formDataToSubmit = new FormData();
    formDataToSubmit.append('name', formData.value.name);
    formDataToSubmit.append('description', formData.value.description);
    formDataToSubmit.append('price', formData.value.price);
    formDataToSubmit.append('categoryId', formData.value.categoryId);
    formDataToSubmit.append('freePostId', formData.value.freePostId);
    formDataToSubmit.append('pageOptionId', formData.value.pageOptionId);
    formDataToSubmit.append('conditionId', formData.value.conditionId);
    formDataToSubmit.append('versionId', formData.value.versionId);
    formDataToSubmit.append('platformId', formData.value.platformId);
    formDataToSubmit.append('introduction', formData.value.introduction);
    formDataToSubmit.append('loginId', String(loginId)); 

    if (formData.value.coverImage) {
      formDataToSubmit.append('coverImage', formData.value.coverImage);
    }

    formData.value.images.forEach((image) => {
      if (image.file) {
        formDataToSubmit.append('images', image.file);
      }
    });

    const response = await axios.post(uploadLink, formDataToSubmit, {
      headers: { 
        'Content-Type': 'multipart/form-data',
        'Authorization': `Bearer ${token}`
      }
    });

    if (response.data.state) {
      alert('商品发布成功!');

      // 清空表单数据
      resetFormData();
    } else {
      alert(`商品发布失败: ${response.data.errMessage}`);
    }
  } catch (error) {
    console.error('Error submitting form:', error);
  }
};

// 重置表单内容
const resetFormData = () => {
  formData.value = {
    loginId,
    name: '',
    description: '',
    price: '',
    categoryId: '',
    freePostId: '',
    pageOptionId: '',
    conditionId: '',
    versionId: '',
    platformId: '',
    introduction: '',
    coverImage: null,
    images: Array.from({ length: 1 }, () => ({ file: null, url: null }))
  };

  // 清空封面预览
  filePreviewUrl.value = null;

  // 清空多图片上传预览
  multiFileInputs.value.forEach(input => {
    if (input) {
      input.value = '';
    }
  });
};



const getGoods = (filterObject: { name: string; platform: string; sortType: string; categoriesId: number }) => {
  
};

onMounted(() => {
  getCategories();
  getAllFreePost();
  getAllPage();
  getAllFineness();
  getAllVersion();
  getAllPlatform();
});
</script>



<style scoped>
.release-container {
  margin-top: 70px;
  height: 850px;
  border: #ccc solid 1px;
  padding-bottom: 20px;
}

.release-box-showInfo {
  width: 100%;
  height: 80%;
}

.multi-upload-container {
  display: flex;
  flex-wrap: wrap;
  gap: 10px; /* 每个上传框之间的间距 */
  margin-top: 20px;
}

.release-section {
  position: relative; /* 新增此行 */
  background-size: contain; /* 确保图片完整显示并适应容器 */
  background-position: center; /* 图片居中 */
  background-repeat: no-repeat; /* 防止重复 */
  width: 100px; /* 增加宽度，使内容区域更大 */
  height: 100px; /* 增加高度，使内容区域更大 */
  display: flex;
  justify-content: center; /* 水平居中 */
  align-items: center; /* 垂直居中 */
  cursor: pointer;
  border: 2px dashed #ccc; /* 添加虚线边框 */
  padding: 20px; /* 使内容与边框之间有间距 */
  border-radius: 8px; /* 使边框角更圆滑 */
  overflow: hidden; /* 确保图片不会超出边界 */
}

.release-section img {
  width: 100%;
  height: 100%;
  object-fit: contain; /* 确保图片保持比例并完整显示 */
}
.delete-button {
  position: absolute;
  top: 5px;
  right: 5px;
  width: 20px;
  height: 20px;
  background-color: red;
  color: white;
  display: flex;
  justify-content: center;
  align-items: center;
  border-radius: 50%;
  cursor: pointer;
  font-size: 16px;
  line-height: 20px;
}
.release-baseInfo{
    height: 10%;
    width: 100%;
    display: flex;
    flex-direction: row;
    align-items: center;
}
.release-name,.release-price,.release-blurb{
    width: 34%;
    height: 100%;
    border-right: solid Silver 1px;
    border-top: solid Silver 1px;
    border-bottom: solid Silver 1px;
    cursor: pointer;
    display: flex;
    align-items: center;
    justify-content: center;
}
.release-intro-container{
    width: 100%;
    height: 30%;
}
.release-select-one{
    width: 100%;
    height: 5%;
    display: flex;
    flex-direction: row;
    align-items: center;
}
.release-select-two{
    width: 100%;
    height: 5%;
    display: flex;
    flex-direction: row;
    align-items: center;
}
.release-category,.release-free-post,.release-page-options,.release-Platform,.release-Fineness,.release-version{
    width: 34%;
    height: 100%;
    border-right: solid Silver 1px;
    border-top: solid Silver 1px;
    border-bottom: solid Silver 1px;
    cursor: pointer;
    display: flex;
    align-items: center;
    justify-content: center;
}
.release-intro{
    width: 99.7%;
    height: 100%;
    resize: none; 
}
.release-button{
  height: 35px;
  margin-top: 10px;
  margin-left: 50%;
  cursor: pointer;
}
</style>